package com.rookie.tool.module.util.ai.util;


import com.rookie.tool.module.util.ai.constant.CommonConstant;
import com.rookie.tool.module.util.ai.entity.FontResult;
import com.rookie.tool.module.util.io.CommonIoUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 图片识别工具
 *
 * @author rookie
 */
public class GeneralBasicUtils {

    private final static String TOKEN = TokenUtils.getToken(CommonConstant.BAI_DU_CLIENT_ID, CommonConstant.BAI_DU_CLIENT_ID);

    @Getter
    @AllArgsConstructor
    private enum ItemUrl{

        /**
         * 基础版
         */
        BASE_URL("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"),
        /**
         * 高精度版
         */
        HEIGHT_URL("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic");

        private String url;

    }

    public static FontResult extractFont(String url,String img) {

        url += "?access_token=" + TOKEN;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/x-www-form-urlencoded");
        try {
            byte[] bytes = FileUtil.readFileByBytes(img);
            String imgStr = Base64.getEncoder().encodeToString(bytes);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            HttpEntity<Object> httpEntity = new HttpEntity<>(("image=" + imgParam).getBytes(StandardCharsets.UTF_8), httpHeaders);
            return TokenUtils.restTemplate.postForObject(url, httpEntity, FontResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args){
        StringBuilder text = new StringBuilder();
        FontResult result = extractFont(ItemUrl.HEIGHT_URL.getUrl(),"D:\\g\\【www.zcdby.com】高性能mysql[第2版]33.png");
        text.append(extractText(result));
        CommonIoUtils.downloadFile(new ByteArrayInputStream(text.toString().getBytes()), "D:\\g\\转换后的文字.md");
    }

    private static StringBuilder extractText(FontResult result) {
        StringBuilder text = new StringBuilder();
        if (result == null) {
            return text;
        }
        result.getWordsResult().forEach(p -> {
            text.append(p.getWords()).append("\n");
        });
        return text;
    }


}
